#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"

ListNode* BuyNewNode(ElementType x)
{
	ListNode* NewNode = (ListNode*)malloc(sizeof(ListNode));
	if (NewNode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	NewNode->data = x;
	NewNode->next = NULL;
	NewNode->prev = NULL;

	return NewNode;
}

ListNode* ListInit(void)
{
	ListNode* phead = BuyNewNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListDestory(ListNode* p)
{
	ListNode* pp = p->next;
	while (pp != p)
	{
		ListNode* next = pp->next;
		free(pp);
		pp = next;
	}
	free(p);
	p = NULL;
}

void ListPushBack(ListNode* p, ElementType x)
{
	//ListNode* tail = p->prev;
	//ListNode* NewNode = BuyNewNode(x);

	//tail->next = NewNode;
	//NewNode->prev = tail;
	//NewNode->next = p;
	//p->prev = NewNode;
	ListInsert(p, x);
}

void ListPrint(ListNode* p)
{
	ListNode* pp = p->next;
	while (pp != p)
	{
		printf("%d ", pp->data);
		pp = pp->next;
	}
	printf("\n");
}

void ListPopBack(ListNode* p)
{
	assert(p->next != p);
	ListNode* pp = p;
	while (pp->next != p)
	{
		pp = pp->next;
	}
	pp->prev->next = p;
	p->prev = pp->prev;
	free(pp);
	pp = NULL;
}

void ListPushFront(ListNode* p, ElementType x) 
{
	/*ListNode* NewNode = BuyNewNode(x);

	NewNode->next = p->next;
	NewNode->prev = p;
	p->next->prev = NewNode;
	p->next = NewNode;*/
	ListInsert(p->next, x);
}

void ListPopFront(ListNode* p)
{
	//assert(p->next != p);
	//ListNode* pp = p->next;
	//ListNode* prev = pp->prev;
	//ListNode* next = pp->next;
	//free(pp);
	//pp = NULL;
	//prev->next = next;
	//next->prev = prev;
	ListErase(p->next);
}

ListNode* ListFind(ListNode* p, ElementType x)
{
	assert(p->next != p);
	ListNode* pp = p->next;
	while (pp != p)
	{
		if(pp->data == x)
			return pp ;
		pp = pp->next;
	}
	return NULL;
}

void ListInsert(ListNode* p, ElementType x)
{
	assert(p);
	ListNode* NewNode = BuyNewNode(x);
	ListNode* prev = p->prev;
	prev->next = NewNode;
	NewNode->prev = prev;
	NewNode->next = p;
	p->prev = NewNode;
}

void ListErase(ListNode* p)
{
	assert(p);
	ListNode* prev = p->prev;
	ListNode* next = p->next;
	free(p);
	p = NULL;
	prev->next = next;
	next->prev = prev;
}